package cn.itcast.bos.web.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller(value="controller01")
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Autowired
	// 注入RedisTemplate模板 完成存储邮件激活码
	private RedisTemplate<String, String> redisTemplate;
	
	@Autowired //注入jmsTemplate模板,完成发短息   发激活邮件的  消息
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	// 手机发送验证码=================================== 1
	// =======================================
	@Action(value = "customer_sendSms")
	public String sendSms() throws UnsupportedEncodingException {
		// 手机号 保存在 Customer对象中
		// 生成短信验证码
		String randomCode = RandomStringUtils.randomNumeric(4);

		// 将短信验证码 存到 session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成手机验证码是:" + randomCode);

		// 编辑短信内容
		//final String msg = "尊敬的用户您好,本次获取的验证码为:" + randomCode + ",服务电话:4006184000";
		//final String msg = randomCode + ",服务电话:4006184000";
		final String msg = ""+randomCode + ",服务电话:4006184000";
		
		//调用MQ服务,发送一条消息
		jmsTemplate.send("bos_sms", new MessageCreator(){
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}});
		return NONE;
		

		// 调用MQ服务,发送一条信息

	}

	// 属性驱动 提交注册表单
	private String checkCode;

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	// 提交注册表单 ==================================== 2
	// =================================================
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 1.短信验证码校验----------------------------------------------------
		// 1.1 校验短信验证码 如果不通过,则跳回注册页面
		// 从session 中获得 生成的短信验证码
		String checkCodeSession = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(model.getTelephone());
		if (checkCodeSession == null || !checkCodeSession.equals(checkCode)) {
			System.out.println("短信验证码错误......");
			return INPUT;
		}
		// 1.2校验通过 调用webService 连接CRM 保存客户信息
		WebClient
				.create("http://localhost:9002/crm_management/services"
						+ "/customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("客户注册成功.....");
		//2.优化   发送一封激活邮件改为发送一个消息给activemq  
		// 2.1生成激活码
			final String activeCode = RandomStringUtils.randomNumeric(32);

		// 2.2将激活码保存到redis,设置24小时后失效
		redisTemplate.opsForValue().set(model.getTelephone(), activeCode);
		
		//2.3 调用activemq发送一条消息
		jmsTemplate.send("bos_mail",new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("activeCode", activeCode);//激活码
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("email", model.getEmail());
				
				return mapMessage;
			}
		});
		
		/*// 2.发送一封激活邮件-----------------------------------------------------
		// 2.1生成激活码
		String activeCode = RandomStringUtils.randomNumeric(32);

		// 2.2将激活码保存到redis,设置24小时后失效
		redisTemplate.opsForValue().set(model.getTelephone(), activeCode);

		// 2.3调用Mailutils发送激活邮件
		String content = "尊敬的客户您好,请于24小时以内,进行邮箱账户的绑定,点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activeCode=" + activeCode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());*/

		return SUCCESS;
	}

	private String activeCode;

	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}

	// 激活邮电的 ===================== 3 ==================================
	@Action(value = "customer_activeMail")
	public String activeMail() throws IOException {
		// 中文乱码处理 因为发送到页面的信息 包含中文
		ServletActionContext.getResponse().setContentType(
				"text/html;charset:utf-8");
		// 1.判断激活码是否有效
		String activeCodeRedis = redisTemplate.opsForValue().get(
				model.getTelephone());
		if (activeCodeRedis == null || !activeCodeRedis.equals(activeCode)) {
			// 激活码无效
			ServletActionContext.getResponse().getWriter()
					.println("激活码无效,请登录系统,重新绑定邮箱!");
		} else {
			// 激活码有效
			// 防止重复绑定
			// 1.1调用CRM_webService 查询客户信息,判断是否已经绑定
			Customer customer = WebClient
					.create("http://localhost:9002/crm_management/services"
							+ "/customerService/customer/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() == null || customer.getType() != 1) {
				// 没有绑定 ,进行绑定 即进行修改操作,应该使用put方法
				WebClient
						.create("http://localhost:9002/crm_management/services/customerService/customer/updateType/"
								+ model.getTelephone()).get();

				ServletActionContext.getResponse().getWriter()
						.println("邮箱绑定成功!");
			} else {
				ServletActionContext.getResponse().getWriter()
						.println("邮箱已经绑定过,无需重复绑定!");
			}
			// 删除redis的激活码
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}

}
